package com.anxin.act.pushProcess.service;

import com.ai.aif.log4x.audit.common.AuditLog;
import com.ai.aif.log4x.audit.common.AuthCode;
import com.ai.aif.log4x.audit.common.SvcType;
import com.ai.aif.log4x.common.datetime.SysDate;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.anxin.act.pushProcess.entity.*;
import com.anxin.act.task.entity.ViewHiTask;
import com.anxin.act.task.entity.ViewRuTask;
import com.anxin.act.task.entity.WfPushLog;
import com.anxin.act.task.service.ActDockingSend;
import com.anxin.act.task.service.WfPushLogService;
import com.anxin.act.utils.ActUtils;
import com.anxin.common.exception.CustomException;
import com.anxin.common.utils.DateUtils;
import com.anxin.common.utils.IdGen;
import com.anxin.common.utils.LogUtils;
import com.anxin.common.utils.StringUtils;
import com.anxin.common.utils.http.HttpClientUtils;
import com.anxin.common.utils.ip.IpUtils;
import com.anxin.common.utils.sys.UserUtils;
import com.anxin.framework.redis.RedisCache;
import com.anxin.framework.security.entity.SysTempToken;
import com.anxin.sys.system.entity.SysUser;
import com.anxin.sys.system.utils.ConfigUtils;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;

@Service
public class ProcessPushService implements ActDockingSend {
    @Value("${taskunified.clientId}")
    private String clientId;

    @Value("${taskunified.clientSecret}")
    private String clientSecret;

    @Value("${taskunified.targetClientId}")
    private String targetClientId;

    @Value("${taskunified.url}")
    private String appTokenUrl;

    @Value("${taskunified.appId}")
    private String appId;

    @Value("${taskunified.todoUrl}")
    private String todoUrl;
    @Value("${oldGq.getAccessTokenUrl}")
    private String getAccessTokenUrl;
    @Value("${taskunified.appKey}")
    private String appKey;
    @Value("${taskunified.vaildUrl}")
    private String appVaildTokenUrl;
    @Value("${taskunified.localUrl}")
    private String localUrl;



    @Autowired
    private RedisCache redisCache;

    @Autowired
    private WfPushLogService wfPushLogService;

    /**
     * 验证appToken
     */
    public String vaildAppToken(String appToken){
        // 业务参数
        JSONObject format = new JSONObject();
        format.put("clientId",clientId);        //发起验证方clientid
        format.put("clientSecret",clientSecret);        //发起验证方clientsecret
        format.put("appToken", appToken);
        LogUtils.info("请求验证appToken参数：" + clientId+":"+clientSecret+":"+appToken);
        // 接口参数
        String ydAccesstoken =  this.getAccesstoken();
        String result = HttpClientUtils.doPostJson(appVaildTokenUrl+"?format=json&sign=SHA&version=V1.0&timestamp="+ DateUtils.format("yyyyMMddHHmmss",new Date())+"&method=M_ABILITY_UNIUSER_200000024&appId="+appId+"&accessToken="+ydAccesstoken, format.toJSONString());
        LogUtils.info("请求验证appToken结果：" + result);
        AuditLog.buildInterfaceLog()
                .hostIp(IpUtils.getHostIp())
                .type(SvcType.TYPE_0)//枚举值：0-消费方 1-服务方 2-接口平台/网关
                .consumer("股权投资管理系统")
                .provider("集中化人力系统基础平台")
                .serverAddr(appVaildTokenUrl)
                .endpoint(appVaildTokenUrl)
                .serviceName("/bap/gw/rest/sso/apptoken/check")
                .auth(AuthCode.AUTH_CODE_0)//枚举值：0-认证通过 1-认证不通过 2-无认证
                .reqBody(format.toJSONString())
                .rspBody(result)
                .retMsg("服务调用成功")
                .retCode("00000")
                .success(true)
                .startTime(SysDate.currentTime())
                .elapsedTime(10)
                .send();

        return result;
    }

    public String getAccesstoken(){
        String url = getAccessTokenUrl + "&app_id=" + appId + "&app_key=" + appKey;
        String stoken ="";
        try {
            String accessTokenReturnResult = HttpClientUtils.doGet(url);
            LogUtils.info("accessToken返回结果：" + accessTokenReturnResult);
            JSONObject obj = JSONObject.parseObject(accessTokenReturnResult);
            stoken = obj.get("access_token").toString();
            redisCache.deleteObject("ydNewAccesstoken");
            redisCache.setCacheObject("ydNewAccesstoken", stoken, 23, TimeUnit.HOURS);
        }catch (Exception e){
            e.printStackTrace();
        }
        LogUtils.info("accessToken的值：" + stoken);
        JSONObject reqBody = new JSONObject();
        reqBody.put("appId",appId);
        reqBody.put("appKey",appKey);
        AuditLog.buildInterfaceLog()
                .hostIp(IpUtils.getHostIp())
                .type(SvcType.TYPE_0)//枚举值：0-消费方 1-服务方 2-接口平台/网关
                .consumer("股权投资管理系统")
                .provider("集中化人力系统基础平台")
                .serverAddr(appVaildTokenUrl)
                .endpoint(appVaildTokenUrl)
                .serviceName("/bap/gw/rest/sso/apptoken/check")
                .auth(AuthCode.AUTH_CODE_0)//枚举值：0-认证通过 1-认证不通过 2-无认证
                .reqBody(reqBody.toJSONString())
                .rspBody(stoken)
                .retMsg("服务调用成功")
                .retCode("00000")
                .success(true)
                .startTime(SysDate.currentTime())
                .elapsedTime(10)
                .send();
        return stoken;
    }

    /**
     *  调用统一用户申请appToken
     */
    public String getAppToken(String targetClientId){
        // 业务参数
        JSONObject format = new JSONObject();
        format.put("clientId",clientId);        //发起方clientid
        format.put("clientSecret",clientSecret);        //发起方clientsecret
        format.put("targetClientId",targetClientId);        //目标clientid
        LogUtils.info("请求appToken参数：" + clientId+":"+clientSecret+":"+targetClientId);
        String result = "";
        try {
            // 接口参数
            String ydAccesstoken =  this.getAccesstoken();
            result = HttpClientUtils.doPostJson(appTokenUrl+"?format=json&sign=SHA&version=V1.0&timestamp="+DateUtils.format("yyyyMMddHHmmss",new Date())+"&method=M_ABILITY_UNIUSER_200000023&appId="+appId+"&accessToken="+ydAccesstoken, format.toJSONString());
            LogUtils.info("请求appToken结果：" + result);
            if(StringUtils.isNotBlank(result)){
                JSONObject resultObj = JSONObject.parseObject(result);
                JSONObject object = JSONObject.parseObject(resultObj.get("result").toString());
                if(object.get("resultCode") != null){
                    String resultCode = object.get("resultCode").toString();
                    AuditLog.buildInterfaceLog()
                            .hostIp(IpUtils.getHostIp())
                            .type(SvcType.TYPE_0)//枚举值：0-消费方 1-服务方 2-接口平台/网关
                            .consumer("股权投资管理系统")
                            .provider("集中化人力系统基础平台")
                            .serverAddr(appTokenUrl)
                            .endpoint(appTokenUrl)
                            .serviceName("/bap/gw/rest/sso/apptoken/acquire")
                            .auth(AuthCode.AUTH_CODE_0)//枚举值：0-认证通过 1-认证不通过 2-无认证
                            .reqBody(format.toJSONString())
                            .rspBody(result)
                            .retMsg("服务调用成功")
                            .retCode("00000")
                            .success(true)
                            .startTime(SysDate.currentTime())
                            .elapsedTime(10)
                            .send();
                    if(StringUtils.equals(resultCode,"000000")){
                        if(object.get("appToken") != null){
                            // 统一代办appToken
                            return object.get("appToken").toString();
                        } else {
                            throw new CustomException(result);
                        }
                    } else {
                        throw new CustomException(result);
                    }
                }else{
                    throw new CustomException(result);
                }
            } else {
                throw new CustomException("调用appToken接口失败");
            }
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 创建待办对象
     */
    public ViewRuTask getRuTaskInfo(String actId, String menuKey,String username,String title){
        ViewRuTask viewRuTask = new ViewRuTask();
        viewRuTask.setActId(actId);
        viewRuTask.setMenukKey(menuKey);
        viewRuTask.setType("RW");
        viewRuTask.setTaskId(actId+username);
        viewRuTask.setTitle(title);
        viewRuTask.setProcessName("投资经理维护数据");
        viewRuTask.setTaskName(title);
        viewRuTask.setApplyLoginName(username);
        viewRuTask.setId(IdGen.uuid());
        viewRuTask.setAssignee(username);
        return viewRuTask;
    }

    public ViewRuTask setRuTaskInfo(String userId,String actId, String menuKey, String username, String title) {
        ViewRuTask viewRuTask = new ViewRuTask();
        viewRuTask.setAssigneeId(userId);
        viewRuTask.setActId(actId);
        viewRuTask.setMenukKey(menuKey);
        viewRuTask.setType("RW");
        viewRuTask.setTaskId(actId + username);
        viewRuTask.setTitle(title);
        viewRuTask.setProcessName("投资经理维护数据");
        viewRuTask.setTaskName(title);
        viewRuTask.setApplyLoginName(username);
        viewRuTask.setId(IdGen.uuid());
        viewRuTask.setAssignee(username);
        return viewRuTask;
    }

    /**
     * 创建已办对象
     */
    public ViewHiTask getHiTaskInfo(String actId, String menuKey,String username,String title){
        ViewHiTask viewHiTask = new ViewHiTask();
        viewHiTask.setActId(actId);
        viewHiTask.setMenukKey(menuKey);
        viewHiTask.setType("RW");
        viewHiTask.setTaskId(actId+username);
        viewHiTask.setTitle(title);
        viewHiTask.setProcessName("投资经理维护数据");
        viewHiTask.setTaskName(title);
        viewHiTask.setApplyLoginName(username);
        viewHiTask.setId(IdGen.uuid());
        viewHiTask.setAssignee(username);
        return viewHiTask;
    }

    /**
     * 统一代办（待办或已办采集接口）
     * @param viewRuTask
     */
    @Override
    public void sendTodoTask(SysTempToken sysTempToken, ViewRuTask viewRuTask, String userId, String userName) {
        Map<String,String> headerMap = new HashMap<>();
        try {
            LogUtils.info("开始推送统一待办");
            String appToken = this.getAppToken(this.targetClientId);
            headerMap.put("securityKey",appToken);
            headerMap.put("appId",clientId);
            Map<String, Object> processVar = ActUtils.getProcessVar(viewRuTask.getActId());
            String businessKey = ActUtils.getBusinessKey(viewRuTask.getActId());
            // 已对接流程标识
            String actFlow = ConfigUtils.get("act_flow");
            if (StringUtils.isNotBlank(businessKey) && actFlow.contains(businessKey)){
                return;
            }
            // 流程信息
            ProcessDefVO processDefVO = new ProcessDefVO();
            processDefVO.setInstanceId(viewRuTask.getActId());
            processDefVO.setStartFlag("false");
            processDefVO.setEndFlag("false");
            processDefVO.setDefinitionId(viewRuTask.getTaskId());
            processDefVO.setDefinitionName(viewRuTask.getTitle());
            if(StringUtils.isNotBlank(businessKey)){
                processDefVO.setProcessTypeId(businessKey);
            } else {
                processDefVO.setProcessTypeId(viewRuTask.getMenukKey());
            }
            processDefVO.setProcessTypeName(viewRuTask.getProcessName());
            processDefVO.setActivityId(viewRuTask.getTaskId());
            processDefVO.setActivityName(viewRuTask.getTaskName());
            //其他业务字段
            OtherFieldVO otherFieldVO = new OtherFieldVO();
            otherFieldVO.setIsCollectFlag("1");
            otherFieldVO.setCollectAppId("null");
            // 文档信息
            DocInfoVO docInfoVO = new DocInfoVO();
            docInfoVO.setDocInsId(viewRuTask.getTaskId());
            docInfoVO.setDocState("1");
            docInfoVO.setItemTitle(viewRuTask.getTitle());
            SysUser applyUser = UserUtils.getUserByUserName(viewRuTask.getApplyLoginName());
            UserInfoVO userInfoVO1 = new UserInfoVO();
            userInfoVO1.setUserId(applyUser.getDeputyAccountNumber());
            userInfoVO1.setUserName(applyUser.getNickName());
            userInfoVO1.setIdType("0");
            docInfoVO.setDrafter(userInfoVO1);
            docInfoVO.setCreateDept(applyUser.getDept().getDeptName());
            if(processVar != null && processVar.get("applyTime") != null){
                docInfoVO.setDocCreateTime(new Date(Long.parseLong(processVar.get("applyTime").toString())).getTime());
            } else {
                docInfoVO.setDocCreateTime(System.currentTimeMillis());
            }
            docInfoVO.setDocTypeId(clientId);
            docInfoVO.setDocTypeName("股权投资管理系统");
            docInfoVO.setIsMyDoc("Y");
            //接口参数对象
            ProcessVO processVO = new ProcessVO();
            processVO.setItemId(viewRuTask.getTaskId());
            processVO.setItemType("0");
            // 判断是否为真实流程。taskType = RW 为手动创造的待办
            if(StringUtils.equals(viewRuTask.getType(),"RW")){
                // menuKey = 'JD' 为季度数据更新， menuKey = 'BG' 为投后评估报告
                processVO.setItemUrl(localUrl+"/unifiedTask?taskId=" + viewRuTask.getId()+"&taskStatus=DB&taskType=RW&menuKey="+ viewRuTask.getMenukKey());
                processVO.setLimit(1);
                WfPushLog wfPushLog = new WfPushLog();
                wfPushLog.setPushType(viewRuTask.getMenukKey());
                wfPushLog.setStatus ("SUCCESS");
                wfPushLog.setActId(viewRuTask.getActId());
                wfPushLog.setTaskId(viewRuTask.getId());
                wfPushLog.setActAssignee(viewRuTask.getAssigneeId());
                WfPushLog pushLogBefore = wfPushLogService.selectWfPushLog(wfPushLog);
                if (pushLogBefore != null && StringUtils.isNotBlank(pushLogBefore.getId())) {
                    wfPushLog.setId(pushLogBefore.getId());
                }
                wfPushLog.setPushTime(DateUtils.getNowDate());
                wfPushLog.setActTitle(viewRuTask.getTitle());
                wfPushLog.setActOwner(viewRuTask.getApplyLoginName());
                wfPushLogService.save(wfPushLog);
            }else {
                processVO.setLimit(0);
                processVO.setItemUrl(sysTempToken.getUseUrl() + "/unifiedTask?taskId=" + viewRuTask.getId() + "&taskStatus=DB");
                processVO.setItemMOAUrl(localUrl+"/gqtzmobile/unifiedTask?taskId=" + viewRuTask.getId()+"&taskStatus=DB");
                WfPushLog wfPushLog = new WfPushLog();
                wfPushLog.setPushType("TODO");
                wfPushLog.setActId(viewRuTask.getActId());
                wfPushLog.setTaskId(viewRuTask.getId());
                wfPushLog.setPushTime(DateUtils.getNowDate());
                wfPushLog.setActTitle(viewRuTask.getTitle());
                wfPushLog.setActOwner(viewRuTask.getApplyLoginName());
                wfPushLog.setActAssignee(viewRuTask.getAssigneeId());
                wfPushLogService.save(wfPushLog);
            }
            if(processVar != null  && processVar.get("applyTime") != null) {
                processVO.setItemCreateTime(new Date(Long.parseLong(processVar.get("applyTime").toString())).getTime());
            }else{
                processVO.setItemCreateTime(System.currentTimeMillis());
            }
            processVO.setLastUpdateTime(System.currentTimeMillis());
            processVO.setOtherField(otherFieldVO);
            // 代办审批人信息
            UserInfoVO userInfoVO = new UserInfoVO();
            SysUser user = new SysUser();
            if(StringUtils.isNotBlank(userId)){
                user = UserUtils.getUser(userId);
            } else {
                user = UserUtils.getUserByUserName(viewRuTask.getAssignee());
            }
            userInfoVO.setUserId(user.getDeputyAccountNumber());
            userInfoVO.setUserName(user.getNickName());
            userInfoVO.setOrgId(user.getOrgCode());
            userInfoVO.setIdType("0");
            userInfoVO.setOrgName(user.getDept().getDeptName());
            // 测试数据
//        userInfoVO.setUserId("liuzhikun@hq.cmcc");
//        userInfoVO.setUserName("刘志坤");
//        userInfoVO.setIdType("0");
//        userInfoVO.setOrgId("1800025112");
//        userInfoVO.setOrgName("综合行政部（董事会办公室）");
            // 代办信息不存在流程结束
            processVO.setReceiver(userInfoVO);
            if (StringUtils.isNotBlank(user.getDeputyAccountNumber()) && user.getDeputyAccountNumber().indexOf("@") >= 0) {
                int i = user.getDeputyAccountNumber().indexOf("@");
                processVO.setRegion(user.getDeputyAccountNumber().substring(i,user.getDeputyAccountNumber().length()).toUpperCase());
            } else {
                processVO.setRegion("@HQ.CMCC");
            }

//        processVO.setRegion(user.getId());
            processVO.setAppId(clientId);
            processVO.setAppName("股权投资管理系统");
            processVO.setProcessDef(processDefVO);
            processVO.setDocInfo(docInfoVO);
            List<UserInfoVO> userInfoVOList = new ArrayList<>();
            String lastAssignee = ActUtils.getLastAssignee(viewRuTask.getActId());
            SysUser userByUserName = UserUtils.getUserByUserName(lastAssignee);
            UserInfoVO userInfoVO2 = new UserInfoVO();
            if(userByUserName != null){
                userInfoVO2.setUserId(userByUserName.getDeputyAccountNumber());
                userInfoVO2.setUserName(userByUserName.getNickName());
                userInfoVO2.setIdType("0");
                userInfoVO2.setOrgId(userByUserName.getOrgCode());
                userInfoVO2.setOrgName(userByUserName.getDept().getDeptName());
                userInfoVOList.add(userInfoVO2);
            } else {
                userInfoVO2.setUserId(applyUser.getDeputyAccountNumber());
                userInfoVO2.setUserName(applyUser.getNickName());
                userInfoVO2.setIdType("0");
                userInfoVO2.setOrgId(applyUser.getOrgCode());
                userInfoVO2.setOrgName(applyUser.getDept().getDeptName());
                userInfoVOList.add(userInfoVO2);
            }
            processVO.setLastHandler(userInfoVOList);
            LogUtils.info("发送统一待办：" + JSON.toJSONString(processVO));
            String result = HttpClientUtils.doPostHeaderJson(todoUrl + "/backlogs/api/v3/todo", headerMap, JSON.toJSONString(processVO));
            AuditLog.buildInterfaceLog()
                    .hostIp(IpUtils.getHostIp())
                    .type(SvcType.TYPE_0)//枚举值：0-消费方 1-服务方 2-接口平台/网关
                    .consumer("股权投资管理系统")
                    .provider("全国统一待办")
                    .serverAddr(todoUrl)
                    .endpoint(todoUrl)
                    .serviceName("/backlogs/api/v3/todo")
                    .auth(AuthCode.AUTH_CODE_0)//枚举值：0-认证通过 1-认证不通过 2-无认证
                    .reqBody( JSON.toJSONString(processVO))
                    .rspBody(result)
                    .retMsg("服务调用成功")
                    .retCode("00000")
                    .success(true)
                    .startTime(SysDate.currentTime())
                    .elapsedTime(10)
                    .send();
            LogUtils.info("发送统一待办返回结果：" + result);
        } catch (Exception e){
            WfPushLog wfPushLog = new WfPushLog(viewRuTask);
            wfPushLogService.save(wfPushLog);
            e.printStackTrace();
        }
    }



    @Override
    public void delTodoTask(String actId, String taskId, String userId, String userName) {
        Map<String,String> headerMap = new HashMap<>();
        try {
            String businessKey = ActUtils.getBusinessKey(actId);
            String actFlow = ConfigUtils.get("act_flow");
            if (StringUtils.isNotBlank(businessKey) && actFlow.contains(businessKey)){
                return;
            }
            String appToken = this.getAppToken(this.targetClientId);
            headerMap.put("securityKey",appToken);
            headerMap.put("appId",clientId);
            ProcessVO processVO = new ProcessVO();
            processVO.setItemId(taskId);
            processVO.setItemUrl(localUrl+"/unifiedTask?taskId=" + taskId+"&taskStatus=YB");
            processVO.setItemMOAUrl(localUrl+"/gqtzmobile/unifiedTask?taskId=" + taskId+"&taskStatus=YB");
            processVO.setItemType("4");
            processVO.setLastUpdateTime(System.currentTimeMillis());
            // 代办审批人信息
            UserInfoVO userInfoVO = new UserInfoVO();
            SysUser user = UserUtils.getUserByUserName(userName);
            userInfoVO.setUserId(user.getDeputyAccountNumber());
            userInfoVO.setUserName(user.getNickName());
            userInfoVO.setOrgId(user.getOrgCode());
            userInfoVO.setIdType("0");
            userInfoVO.setOrgName(user.getDept().getDeptName());
            processVO.setReceiver(userInfoVO);
            processVO.setAppId(clientId);
            LogUtils.info("注销待办：" + JSON.toJSONString(processVO));
            String result = HttpClientUtils.doPostHeaderJson(todoUrl + "/backlogs/api/v3/chang/status", headerMap, JSON.toJSONString(processVO));
            LogUtils.info("注销待办返回结果：" + result);
            AuditLog.buildInterfaceLog()
                    .hostIp(IpUtils.getHostIp())
                    .type(SvcType.TYPE_0)//枚举值：0-消费方 1-服务方 2-接口平台/网关
                    .consumer("股权投资管理系统")
                    .provider("全国统一待办")
                    .serverAddr(todoUrl)
                    .endpoint(todoUrl)
                    .serviceName("/backlogs/api/v3/chang/status")
                    .auth(AuthCode.AUTH_CODE_0)//枚举值：0-认证通过 1-认证不通过 2-无认证
                    .reqBody( JSON.toJSONString(processVO))
                    .rspBody(result)
                    .retMsg("服务调用成功")
                    .retCode("00000")
                    .success(true)
                    .startTime(SysDate.currentTime())
                    .elapsedTime(10)
                    .send();
        } catch (Exception e){
            WfPushLog wfPushLog = new WfPushLog();
            wfPushLogService.save(wfPushLog);
            e.printStackTrace();
        }
    }

    @Override
    public void updateTodoTask(String actId, String taskId, String userId, String userName) {
        Map<String, String> headerMap = new HashMap<>();
        try {
            String businessKey = ActUtils.getBusinessKey(actId);
            String actFlow = ConfigUtils.get("act_flow");
            if (StringUtils.isNotBlank(businessKey) && actFlow.contains(businessKey)) {
                return;
            }
            String appToken = this.getAppToken(this.targetClientId);
            headerMap.put("securityKey", appToken);
            headerMap.put("appId", clientId);
            ProcessVO processVO = new ProcessVO();
            processVO.setItemId(taskId);
            processVO.setLimit(1);
            processVO.setItemType("2");
            String moaTaskId = wfPushLogService.selectTaskId(actId,userId);
            processVO.setItemUrl(localUrl + "/unifiedTask?taskId=" + moaTaskId + "&taskStatus=YB&taskType=RW&menuKey=JD");
            processVO.setLastUpdateTime(System.currentTimeMillis());
            // 代办审批人信息
            UserInfoVO userInfoVO = new UserInfoVO();
            SysUser user = UserUtils.getUserByUserName(userName);
            userInfoVO.setUserId(user.getDeputyAccountNumber());
            userInfoVO.setUserName(user.getNickName());
            userInfoVO.setOrgId(user.getOrgCode());
            userInfoVO.setIdType("0");
            userInfoVO.setOrgName(user.getDept().getDeptName());
            processVO.setReceiver(userInfoVO);
            processVO.setAppId(clientId);
            LogUtils.info("注销待办：" + JSON.toJSONString(processVO));
            String result = HttpClientUtils.doPostHeaderJson(todoUrl + "/backlogs/api/v3/chang/status", headerMap, JSON.toJSONString(processVO));
            LogUtils.info("注销待办返回结果：" + result);
            AuditLog.buildInterfaceLog()
                    .hostIp(IpUtils.getHostIp())
                    .type(SvcType.TYPE_0)//枚举值：0-消费方 1-服务方 2-接口平台/网关
                    .consumer("股权投资管理系统")
                    .provider("全国统一待办")
                    .serverAddr(todoUrl)
                    .endpoint(todoUrl)
                    .serviceName("/backlogs/api/v3/chang/status")
                    .auth(AuthCode.AUTH_CODE_0)//枚举值：0-认证通过 1-认证不通过 2-无认证
                    .reqBody(JSON.toJSONString(processVO))
                    .rspBody(result)
                    .retMsg("服务调用成功")
                    .retCode("00000")
                    .success(true)
                    .startTime(SysDate.currentTime())
                    .elapsedTime(10)
                    .send();
        } catch (Exception e) {
            WfPushLog wfPushLog = new WfPushLog();
            wfPushLogService.save(wfPushLog);
            e.printStackTrace();
        }
    }

    /**
     * 发送已办
     * @param viewHiTask
     * @param userId
     * @param userName
     */
    @Override
    public void sendHiTask(ViewHiTask viewHiTask, String userId, String userName) {
        Map<String,String> headerMap = new HashMap<>();
        try {
            String appToken = this.getAppToken(this.targetClientId);
            headerMap.put("securityKey",appToken);
            headerMap.put("appId",clientId);
            Map<String, Object> processVar = ActUtils.getProcessVar(viewHiTask.getActId());
            String businessKey = ActUtils.getBusinessKey(viewHiTask.getActId());
            // 已对接流程标识
            String actFlow = ConfigUtils.get("act_flow");
            if (StringUtils.isNotBlank(businessKey) && actFlow.contains(businessKey)){
                return;
            }
            // 流程信息
            ProcessDefVO processDefVO = new ProcessDefVO();
            processDefVO.setInstanceId(viewHiTask.getActId());
            processDefVO.setStartFlag("false");
            processDefVO.setEndFlag("false");
            processDefVO.setDefinitionId(viewHiTask.getTaskId());
            processDefVO.setDefinitionName(viewHiTask.getTitle());
            if(StringUtils.isNotBlank(businessKey)){
                processDefVO.setProcessTypeId(businessKey);
            } else {
                processDefVO.setProcessTypeId(viewHiTask.getMenukKey());
            }
            processDefVO.setProcessTypeName(viewHiTask.getProcessName());
            processDefVO.setActivityId(viewHiTask.getTaskId());
            processDefVO.setActivityName(viewHiTask.getTaskName());
            //其他业务字段
            OtherFieldVO otherFieldVO = new OtherFieldVO();
            otherFieldVO.setIsCollectFlag("1");
            otherFieldVO.setCollectAppId("null");
            // 文档信息
            DocInfoVO docInfoVO = new DocInfoVO();
            docInfoVO.setDocInsId(viewHiTask.getTaskId());
            docInfoVO.setDocState("1");
            docInfoVO.setItemTitle(viewHiTask.getTitle());
            SysUser applyUser = UserUtils.getUserByUserName(viewHiTask.getApplyLoginName());
            UserInfoVO userInfoVO1 = new UserInfoVO();
            userInfoVO1.setUserId(applyUser.getDeputyAccountNumber());
            userInfoVO1.setUserName(applyUser.getNickName());
            userInfoVO1.setIdType("0");
            docInfoVO.setDrafter(userInfoVO1);
            docInfoVO.setCreateDept(applyUser.getDept().getDeptName());
            if(processVar != null  && processVar.get("applyTime") != null) {
                docInfoVO.setDocCreateTime(new Date(Long.parseLong(processVar.get("applyTime").toString())).getTime());
            }else{
                docInfoVO.setDocCreateTime(System.currentTimeMillis());
            }
            docInfoVO.setDocTypeId(clientId);
            docInfoVO.setDocTypeName("股权投资管理系统");
            docInfoVO.setIsMyDoc("Y");
            //接口参数对象
            ProcessVO processVO = new ProcessVO();
            processVO.setItemId(viewHiTask.getTaskId());
            // 判断是否为真实流程。taskType = RW 为手动创造的待办
            if(StringUtils.equals(viewHiTask.getType(),"RW")){
                // menuKey = 'JD' 为季度数据更新， menuKey = 'BG' 为投后评估报告
                processVO.setItemUrl(localUrl+"/gqtzmobile/unifiedTask?taskId=" + viewHiTask.getId()+"&taskStatus=DB&taskType=RW&menuKey="+ viewHiTask.getMenukKey());
                processVO.setLimit(1);
            }else {
                processVO.setItemUrl(localUrl + "/unifiedTask?taskId=" + viewHiTask.getTaskId() + "&taskStatus=YB");
                processVO.setItemMOAUrl(localUrl + "/gqtzmobile/unifiedTask?taskId=" + viewHiTask.getTaskId() + "&taskStatus=YB");
            }
            processVO.setItemType("2");
            if(processVar != null  && processVar.get("applyTime") != null) {
                processVO.setItemCreateTime(new Date(Long.parseLong(processVar.get("applyTime").toString())).getTime());
            }else{
                processVO.setItemCreateTime(System.currentTimeMillis());
            }
            processVO.setLastUpdateTime(System.currentTimeMillis());
            processVO.setOtherField(otherFieldVO);
            // 代办审批人信息
            UserInfoVO userInfoVO = new UserInfoVO();
            SysUser user = UserUtils.getUserByUserName(viewHiTask.getAssignee());
            userInfoVO.setUserId(user.getDeputyAccountNumber());
            userInfoVO.setUserName(user.getNickName());
            userInfoVO.setOrgId(user.getOrgCode());
            userInfoVO.setIdType("0");
            userInfoVO.setOrgName(user.getDept().getDeptName());
            // 测试数据
//        userInfoVO.setUserId("liuzhikun@hq.cmcc");
//        userInfoVO.setUserName("刘志坤");
//        userInfoVO.setIdType("0");
//        userInfoVO.setOrgId("1800025112");
//        userInfoVO.setOrgName("综合行政部（董事会办公室）");
            // 代办信息不存在流程结束
            processVO.setReceiver(userInfoVO);
            if (StringUtils.isNotBlank(user.getDeputyAccountNumber()) && user.getDeputyAccountNumber().indexOf("@") >= 0) {
                int i = user.getDeputyAccountNumber().indexOf("@");
                processVO.setRegion(user.getDeputyAccountNumber().substring(i,user.getDeputyAccountNumber().length()).toUpperCase());
            } else {
                processVO.setRegion("@HQ.CMCC");
            }

//        processVO.setRegion(user.getId());
            processVO.setAppId(clientId);
            processVO.setAppName("股权投资管理系统");
            processVO.setProcessDef(processDefVO);
            processVO.setDocInfo(docInfoVO);
            List<UserInfoVO> userInfoVOList = new ArrayList<>();
            String lastAssignee = ActUtils.getLastAssignee(viewHiTask.getActId());
            SysUser userByUserName = UserUtils.getUserByUserName(lastAssignee);
            UserInfoVO userInfoVO2 = new UserInfoVO();
            if(userByUserName != null){
                userInfoVO2.setUserId(userByUserName.getDeputyAccountNumber());
                userInfoVO2.setUserName(userByUserName.getNickName());
                userInfoVO2.setIdType("0");
                userInfoVO2.setOrgId(userByUserName.getOrgCode());
                userInfoVO2.setOrgName(userByUserName.getDept().getDeptName());
                userInfoVOList.add(userInfoVO2);
            } else {
                userInfoVO2.setUserId(applyUser.getDeputyAccountNumber());
                userInfoVO2.setUserName(applyUser.getNickName());
                userInfoVO2.setIdType("0");
                userInfoVO2.setOrgId(applyUser.getOrgCode());
                userInfoVO2.setOrgName(applyUser.getDept().getDeptName());
                userInfoVOList.add(userInfoVO2);
            }
            userInfoVOList.add(userInfoVO2);
            processVO.setLastHandler(userInfoVOList);
            LogUtils.info("发送已办：" + JSON.toJSONString(processVO));
            String result = HttpClientUtils.doPostHeaderJson(todoUrl + "/backlogs/api/v3/todo", headerMap, JSON.toJSONString(processVO));
            LogUtils.info("发送已办返回结果：" + result);
            AuditLog.buildInterfaceLog()
                    .hostIp(IpUtils.getHostIp())
                    .type(SvcType.TYPE_0)//枚举值：0-消费方 1-服务方 2-接口平台/网关
                    .consumer("股权投资管理系统")
                    .provider("全国统一待办")
                    .serverAddr(todoUrl)
                    .endpoint(todoUrl)
                    .serviceName("/backlogs/api/v3/todo")
                    .auth(AuthCode.AUTH_CODE_0)//枚举值：0-认证通过 1-认证不通过 2-无认证
                    .reqBody( JSON.toJSONString(processVO))
                    .rspBody(result)
                    .retMsg("服务调用成功")
                    .retCode("00000")
                    .success(true)
                    .startTime(SysDate.currentTime())
                    .elapsedTime(10)
                    .send();
        } catch (Exception e){
            WfPushLog wfPushLog = new WfPushLog(viewHiTask);
            wfPushLogService.save(wfPushLog);
            e.printStackTrace();
        }
    }

    @Override
    public void delHiTask(ViewHiTask viewHiTask, String userId, String userName) {

    }

    public static void main(String[] args) {
//        String sss = "{\"result\":{\"appToken\":\"Q8Nh0kTYYy39gUrVLGaXORnOdbMUBSuUWYFMSHL7RBJnx8JrMk5_z_hd8167QZAo\",\"resultCode\":\"000000\",\"resultMessage\":\"成功\"},\"respDesc\":\"success\",\"instanceId\":\"527ae0ac-81ad-4379-b514-5e93e92ade0e\",\"respCode\":\"00000\"}";
//        JSONObject resultObj = JSONObject.parseObject(sss);
//        JSONObject object = JSONObject.parseObject(resultObj.get("result").toString());
//        String resultCode = object.get("resultCode").toString();
        String aaa = "liuzhikun@hq.cmcc";
        int i = aaa.indexOf("@");
        System.out.println(aaa.substring(i,aaa.length()).toUpperCase());
    }
}
